<template>
  <Table
    ref="tableRef"
    :columns="columns"
    :data="loadData"
    :alert="false"
    bordered
    :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
  >
    <template #operator>
      <tableForm @handle-search="formSearch" ref="tableFormRef" />
      <div style="margin-top: 16px">
        <a-button type="primary" @click="batchTrigger" class="batch-trigger" :loading="loading">
          <SvgIcon name="play-save" width="16" height="16" :color="`#fff`" />
          批量触发
        </a-button>
      </div>
    </template>
    <template #bodyCell="{ column, record, index }">
      <template v-if="column.dataIndex === 'index'"> {{ index + 1 }} </template>
      <template v-if="column.dataIndex === 'pipelineName'">
        <div class="pipeline-name">
          <div class="pipeline-top-box">
            <span
              v-for="(item, inx) in record?.tagList"
              :key="inx"
              class="grouping-box"
              :style="{
                background: TagBgColors[item.color as keyof typeof TagBgColors],
                color: TagColors[item.color as keyof typeof TagColors],
              }"
            >
              {{ item.name }}
            </span>
          </div>
          <a class="ellipsis" :title="record.pipelineName" @click="handelRunningDetial(record)">{{
            record.pipelineName
          }}</a>
        </div>
      </template>
      <template v-if="column.dataIndex === 'recentlyRunStatus'">
        <div class="running-status">
          <SvgIcon
            v-if="record.recentlyRunStatus"
            :name="pipelineStatusMap[record.recentlyRunStatus  as PipelineStatus]?.icon|| '--'"
            :style="{ marginRight: '8px', color: pipelineStatusMap[record.recentlyRunStatus  as PipelineStatus]?.color || '--'}"
            :class="{ 'svg-rotate': record.recentlyRunStatus == PipelineStatus.running }"
          />
          <span :style="{ color: pipelineStatusMap[record.recentlyRunStatus  as PipelineStatus]?.color}">{{
            pipelineStatusMap[record.recentlyRunStatus as PipelineStatus]?.text || '--'
          }}</span>
        </div>
      </template>
      <template v-if="column.dataIndex === 'action'">
        <div class="table-operation">
          <a @click="handelDetial(record)">详情</a>
          <a
            @click="handelEdit(record)"
            v-auth="[
              { objectId: record.componentCode, objectType: ResourceType.component, role: Role.manager },
              { objectId: record.appCode, objectType: ResourceType.app, role: Role.manager },
            ]"
            >编辑</a
          >
          <a-dropdown placement="bottom">
            <SvgIcon class="iconDef" :name="'vertical'" :color="'#1890ff'" width="16" height="16" />
            <template #overlay>
              <a-menu>
                <a-menu-item v-for="item in dropdownList" :key="item.value" @click="item.onClick(record)">
                  <div class="dropdown-item">
                    <span> {{ item.label }} </span>
                  </div>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </template>
    </template>
  </Table>

  <ViewYAMLModal ref="viewYAMLModalRef" />

  <BasicModal
    ref="showActionModal"
    :title="`添加${addType}`"
    width="500px"
    @emit-callback-fn="modalCallbackFn($event)"
    :confirmLoading="editGroupLoading"
  >
    <template #content> <SchemaForm ref="formRef" /></template>
  </BasicModal>
</template>

<script lang="ts" setup>
import tableForm from './tableForm.vue';
import {
  getMyPipelineList,
  getModifyPipelineGroupsList,
  getModifyPipelineTagsList,
  batchTriggerPipeline,
} from '@/api/pipeline';
import { pipelineStatusMap } from '@/settings/commonSettings';
import { PipelineStatus, ResourceType, Role } from '@/enums/pipelineEnum';
import { useForm } from '@/components/SchemaForm/index';
import type { FormSchema } from '@/components/SchemaForm';
import { TagColors, TagBgColors } from '@/enums/commonEnum';
import { message } from 'ant-design-vue';
import ViewYAMLModal from '../../applicationManagement/components/modules/tables/viewYAMLModal.vue';

const columns = [
  { dataIndex: 'index', title: '序号', align: 'center', width: 60 },
  { dataIndex: 'pipelineName', title: '流水线名称', align: 'center', ellipsis: true, width: 180 },
  { dataIndex: 'recentlyRunStatus', title: '最近运行状态', align: 'center', ellipsis: true },
  { dataIndex: 'applicationName', title: '应用', align: 'center', ellipsis: true },
  { dataIndex: 'componentName', title: '组件', align: 'center', ellipsis: true },
  { dataIndex: 'environmentName', title: '环境', align: 'center', ellipsis: true },
  { dataIndex: 'lastTaskName', title: '最近任务', align: 'center', ellipsis: true },
  { dataIndex: 'triggerInfo', title: '触发信息', align: 'center', ellipsis: true },
  { dataIndex: 'recentlyBuildNumber', title: '最新构建号', align: 'center', ellipsis: true },
  { dataIndex: 'totalTaskCount', title: '任务总数', align: 'center', ellipsis: true },
  { dataIndex: 'executedCount', title: '已执行次数', align: 'center', ellipsis: true },
  { dataIndex: 'lastRunStartTime', title: '最近运行开始时间', align: 'center', ellipsis: true },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 160,
  },
];
const emits = defineEmits(['refreshSelectList']);
const selectedRowKeys = ref<string[]>([]);
const [SchemaForm, formRef] = useForm({
  schemas: [] as FormSchema[],
});

enum AddType {
  group = '分组',
  tag = '标签',
}

const props = defineProps({
  activeKey: {
    type: String,
    default: '',
  },
  tagListData: {
    type: Array,
    default: () => [],
  },
  groupListData: {
    type: Array,
    default: () => [],
  },
});

const tableRef = ref<any>(null);
const viewYAMLModalRef = ref<any>(null);
const router = useRouter();
const showActionModal = ref<any>(null);
const addType = ref<AddType>();
const fromSearchData = reactive<Pipeline.MyPipelineQuery>({
  name: '',
  componentLabel: '',
  envUuid: '',
  applicationCode: '',
  status: null,
  triggerWay: null,
  group: '',
  startTimeFrom: '',
  startTimeTo: '',
});
const loading = ref(false);

// table搜索事件
const formSearch = (from: any) => {
  delete from.lastRunTime;
  fromSearchData.name = from.name;
  fromSearchData.status = from.status;
  fromSearchData.applicationCode = from.applicationCode;
  fromSearchData.componentLabel = from.componentLabel;
  fromSearchData.envUuid = from.envUuid;
  fromSearchData.startTimeFrom = from.startTimeFrom;
  fromSearchData.startTimeTo = from.startTimeTo;
  // fromSearchData.own = from.own;
  fromSearchData.triggerWay = from.triggerWay;
  tableRef.value.refresh(true);
};

const editGroupLoading = ref<boolean>(false);
const modalCallbackFn = async (obj: any) => {
  const data = await formRef.validate();
  editGroupLoading.value = true;
  // 添加分组变更
  if (AddType.group === addType.value) {
    let itemObj = {
      pipelineCode: obj.propsData.pipelineCode,
      groupUuidList: data.pipelineGroup,
    };

    await getModifyPipelineGroupsList(itemObj)
      .then(() => {
        message.success('添加成功');
        tableRef.value.refresh(true);
        showActionModal.value.hideModal();
      })
      .finally(() => {
        editGroupLoading.value = false;
      });
  }

  // 添加标签变更
  if (AddType.tag === addType.value) {
    let itemObj = {
      pipelineCode: obj.propsData.pipelineCode,
      tagUuidList: data.pipelineTags,
    };
    await getModifyPipelineTagsList(itemObj)
      .then(() => {
        message.success('添加成功');
        tableRef.value.refresh(true);
        showActionModal.value.hideModal();
      })
      .finally(() => {
        editGroupLoading.value = false;
      });
  }
};

const addGroup = (record: any) => {
  addType.value = AddType.group;
  showActionModal.value.showModal(record);
  emits('refreshSelectList', false);
  nextTick(() => {
    formRef.appendSchemaByField({
      field: 'pipelineGroup',
      label: '流水线分组',
      labelWidth: 100,
      required: true,
      colProps: {
        span: 24,
      },
      componentProps: {
        mode: 'multiple',
        optionFilterProp: 'name',
        fieldNames: { label: 'name', value: 'uuid' },
        options: props.groupListData,
      },
      component: 'Select',
    });
  });
};

const addTag = (record: any) => {
  addType.value = AddType.tag;
  showActionModal.value.showModal(record);
  emits('refreshSelectList', false);
  nextTick(() => {
    formRef.appendSchemaByField({
      field: 'pipelineTags',
      label: '标签',
      labelWidth: 80,
      colProps: {
        span: 24,
      },
      required: true,
      componentProps: {
        mode: 'multiple',
        optionFilterProp: 'name',
        fieldNames: { label: 'name', value: 'uuid' },
        options: props.tagListData,
        defaultValue: record.tagList?.map((item: any) => item.uuid) || [],
      },
      component: 'Select',
    });
  });
};

const onSelectChange = (keys: string[], selections: any) => {
  selectedRowKeys.value = selections.map((item: any) => item.pipelineCode);
};

const batchTrigger = async () => {
  if (selectedRowKeys.value.length == 0) {
    message.warn('请至少选择一条记录');
    return;
  }
  loading.value = true;
  try {
    await batchTriggerPipeline(selectedRowKeys.value);
    message.success('批量触发成功');
    tableRef.value.refresh(true);
    selectedRowKeys.value = [];
  } finally {
    loading.value = false;
  }
};

//运行态详情
const handelRunningDetial = (record: any) => {
  router.push(`/system/pipelineRunning/${record.pipelineCode}`);
};

//编辑态详情
const handelDetial = (record: any) => {
  router.push(`/system/pipelineDetail/info/${record.pipelineCode}`);
};

//表格编辑
const handelEdit = (record: any) => {
  router.push(`/system/pipelineConfig/${record.pipelineCode}`);
};

const viewYAML = (record: any) => {
  viewYAMLModalRef.value.onOpen(record);
};

const goRunHistory = (record: Pipeline.BaseInfo) => {
  router.push(`/system/pipelineRunning/${record.pipelineCode}/runHistory`);
};

const dropdownList = [
  {
    label: 'YAML查看',
    value: 'yaml',
    onClick: (record: any) => viewYAML(record),
  },
  {
    label: '运行历史',
    value: 'history',
    onClick: (record: any) => goRunHistory(record),
  },
  {
    label: '添加分组',
    value: 'addGroup',
    onClick: (record: any) => addGroup(record),
  },
  {
    label: '添加标签',
    value: 'addTag',
    onClick: (record: any) => addTag(record),
  },
];

const loadData = async (parameter: any) => {
  const parameObj = {
    currentPage: parameter.current,
    pageSize: parameter.size,
    condition: { ...fromSearchData },
  };
  const data = await getList(parameObj);
  return data;
};
//获取表格数据
const getList = async (parameObj: any) => {
  return await getMyPipelineList(parameObj).then((res) => {
    const data = {
      total: res.totalCount,
      current: res.currentPage,
      pageSize: res.pageSize,
      records: res?.records || [],
    };
    return data;
  });
};

// 刷新当前列表
const tableFormRef = ref<any>(null);
const refreshTable = (key?: string) => {
  fromSearchData.group = key;
  tableFormRef.value.resetData();
};

defineExpose({
  refreshTable,
});
</script>

<style scoped lang="less">
.pipeline-name {
  display: flex;
  flex-direction: column;
  .pipeline-top-box {
    gap: 8px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 4px;
    flex-wrap: wrap;
    .grouping-box {
      border-radius: 4px;
      display: inline-block;
      font-size: 12px;
      font-weight: 400;
      padding: 0 12px;
    }
  }
}
.running-status {
  display: flex;
  justify-content: center;
  align-items: center;
}

.table-operation {
  display: flex;
  justify-content: center;
  align-items: center;
}

.dropdown-item {
  display: flex;
  align-items: center;
  padding: 0 12px;
  .iconDef {
    margin-right: 8px;
  }
}

:deep(.ant-dropdown-menu-item:hover, .ant-dropdown-menu-submenu-title:hover) {
  background: rgba(37, 144, 255, 0.1);
  color: #1890ff;
}
.batch-trigger {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>
